﻿using Abp.Collections.Extensions;
using Abp.Extensions;
using Mt.Site.Core.WorkFlows.Enum;
using Mt.Site.Core.WorkFlows.Process;
using Mt.Site.Core.WorkFlows.Process.Stores;
using System.Threading.Tasks;

namespace Mt.Site.Core.WorkFlows.Diy.Actions.Impl
{
    public class MenuPickingAction : ActionBase
    {

        public override string UniqueName => WorkFlowConst.OperationName.MenuPickingAction;

        public override string JsActionName => "menuPicking";

        private string MenuIdsKey = WorkFlowConst.FieldName.Content2.Menu.ToPascalCase();

        private readonly IWorkFlowFormDataStore _workFlowFormDataStore;

        public MenuPickingAction(IWorkFlowFormDataStore workFlowFormDataStore)
        {
            _workFlowFormDataStore = workFlowFormDataStore;
        }

        public override async Task<bool> IsShowAsync(IWorkFlowManager manager)
        {
            if (manager.CanOperate(UniqueName))
            {
                var actionState = await manager.CheckActionStateAsync();
                if (actionState == ActionState.Todo)
                {
                    return true;
                }
            }

            return false;
        }

        public override async Task OperateAsync(IWorkFlowManager manager, object data)
        {
            var isShow = await IsShowAsync(manager);
            if (isShow)
            {
                var args = data as ActionArgs;

                string menuIdStr;
                if (args == null || args.UserIdList.IsNullOrEmpty())
                {
                    menuIdStr = "";
                }
                else
                {
                    menuIdStr = args.UserIdList.JoinAsString(WorkFlowConst.SplitChars);
                }

                await _workFlowFormDataStore.UpdateOrInsertSpecialFieldAsync(MenuIdsKey, manager.PaperId, menuIdStr);
            }
        }
    }
}